package com.faxsun.web.controller.stat;

import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.service.PostService;
import com.faxsun.core.service.TagService;

import mblog.web.controller.BaseController;

/**
 * 用于统计文章浏览次数，产品浏览次数
 * 
 * @author songdragon 2015年6月16日
 *
 */
@Controller
@RequestMapping(value = "/stat")
public class ViewStatisticController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(ViewStatisticController.class);

	private static final String postUrl = "/post/view/";
	private static final String productUrl = "/product/view/";

	@Autowired
	PostService postService;

	@Autowired
	TagService tagService;

	@Value("${online.enableStatistic}")
	private String statEnable = "";

	/**
	 * 根据request的referer，记录文章和产品的浏览次数
	 * 
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(value = "/view")
	public void statistic(HttpServletRequest request) {
		String referer = request.getHeader("Referer");
		String ip = getClientIP(request);

		if (this.statEnable.equals("false")) {
			return;
		}

		// TODO: 添加IP黑名单
		if (ip.equals("101.231.32.250")) {
			return;
		}
		if (!StringUtils.isEmpty(referer)) {
			URL url = null;
			try {
				url = new URL(referer);
				String path = url.getPath();
				if (path.startsWith("/faxsun-info")) {
					path = path.replace("/faxsun-info", "");
				}
				if (path.contains(";"))
					path = path.substring(0, path.indexOf(";"));

				if (path.startsWith(postUrl)) {
					String idStr = path.substring(postUrl.length());
					if (idStr.contains(";"))
						idStr = idStr.substring(0, idStr.indexOf(";"));
					Long id = Long.parseLong(idStr);
					// update view of post id
					postService.identityViews(id);
				} else if (path.startsWith(productUrl)) {
					String idStr = path.substring(productUrl.length());
					Long id = Long.parseLong(idStr);
					// update view of product id
					tagService.identityHots(id);
				}

			} catch (MalformedURLException e) {
				log.error("url error", e);
				log.error(referer);
			} catch (Exception e) {
				log.error("Unknown error", e);
				log.error(referer);
			}
		}
	}

	private String getClientIP(HttpServletRequest request) {
		String xForward = request.getHeader("x-forwarded-for");

		if (xForward == null || xForward.length() == 0
				|| xForward.equalsIgnoreCase("unknown")) {
			String proxyClientIP = request.getHeader("Proxy-Client-IP");
			if (proxyClientIP == null || proxyClientIP.length() == 0
					|| "unknown".equalsIgnoreCase(proxyClientIP)) {
				String wlProxyClientIP = request
						.getHeader("WL-Proxy-Client-IP");
				if (wlProxyClientIP == null || wlProxyClientIP.length() == 0
						|| "unknown".equalsIgnoreCase(wlProxyClientIP)) {
					return request.getRemoteAddr();
				}
				return wlProxyClientIP;
			}
			return proxyClientIP;
		}
		return xForward;
	}
}
